import React from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {
    DeviceEventEmitter,
    AppState,
    PushNotificationIOS,
    Platform,
    Linking,
    Alert,
    InteractionManager,
    StatusBar
} from 'react-native';
import Storage from 'react-native-simple-store';
import {
    AccessToken,
    AppUrl,
    CodePushAndroidKey,
    CodePushIosKey,
    UserDidLoggedInNotification,
    UserDidLogoutNotification,
    UserInfoStoreKey,
} from "../base/constants";
import JPush from 'jpush-react-native';
import CodePush from 'react-native-code-push';
import GeoLocation from '@react-native-community/geolocation';
import {authActionCreators, locationActionCreators} from '../actions';
import {ApiClient, Utils} from '../utils';
import {LaunchScreen} from "../components";
import AppContainer from "./AppContainer";
import SignStack from "../pages/auth/SignStack";

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            //showLaunch: Platform.OS !== 'ios'
            showLaunch: false
        };
    }

    render() {
        if (this.state.showLaunch) return <LaunchScreen/>;
        if (this.props.auth.isLoggedIn){
            return <AppContainer/>;
        } else {
            return <SignStack/>;
        }
    }

    UNSAFE_componentWillMount(): void {
        StatusBar.setHidden(false);
        Utils.setStatusBarStyle('default');
    }

    componentDidMount() {
        AppState.removeEventListener('change', this.onAppStateChange);

        const {authActions, locationActions} = this.props;
        DeviceEventEmitter.addListener(UserDidLoggedInNotification, (userinfo) => {
            Storage.update(UserInfoStoreKey, userinfo).then(() => {
                authActions.userDidLoggedIn(userinfo);
            });
            Storage.get('RegistrationID').then(registrationid => {
                ApiClient.post('/jpush', {
                    platform: Platform.OS,
                    registrationid
                });
            });
        });

        DeviceEventEmitter.addListener(UserDidLogoutNotification, () => {
            Storage.delete(UserInfoStoreKey).then(() => {
                authActions.userDidLogout();
            });
            Storage.delete(AccessToken);
        });

        InteractionManager.runAfterInteractions(() => {
            this.checkUserStatus();
            AppState.addEventListener('change', this.onAppStateChange);
        });
        //获取位置信息
        //if (Platform.OS === 'ios') GeoLocation.requestAuthorization();
        GeoLocation.getCurrentPosition(position => {
            //console.log(position);
            locationActions.userLocationDidChanged(position);
            GeoLocation.watchPosition(position => {
                locationActions.userLocationDidChanged(position);
            }, error => {
                console.log(error);
            }, {
                maximumAge: 600000
            });
        },error => {
            console.log(error);
        });

        setTimeout(() => {
            this.setState({
                showLaunch: false
            })
        }, 2000);

        //注册通知
        this.setupJPush();
        //更新版本
        this.checkUpdates();
    }

    onAppStateChange = (appState) => {
        if (Platform.OS === 'ios') {
            //PushNotificationIOS.setApplicationIconBadgeNumber(0);
            JPush.setBadge({
                'badge': 0
            });
        }
        //console.log('appState:'+appState);
        if (appState === 'active') {
            //this.checkLogin();
            //检测新版本
            this.checkVersion();
            this.checkUpdates();
        }
    };

    checkUpdates = () => {
        //热更新
        if (!__DEV__) {
            CodePush.sync({
                updateDialog: false,
                installMode: CodePush.InstallMode.IMMEDIATE,
                deploymentKey: Platform.OS === 'ios' ? CodePushIosKey : CodePushAndroidKey,
            });
        }
    };

    checkUserStatus = () => {
        const {authActions} = this.props;
        Storage.get(UserInfoStoreKey).then(userinfo => {
            if (userinfo) {
                authActions.userDidLoggedIn(res);
            } else {
                authActions.userDidLogout();
            }
        }).catch(error => {
            authActions.userDidLogout();
        });
    };

    registerNotificationIOS = () => {
        PushNotificationIOS.requestPermissions();
        PushNotificationIOS.addEventListener('register', (device_token) => {
            Storage.setItem('DeviceToken', device_token).then(() => {
                ApiClient.post('/apns/device_token', {device_token});
            });
        });
        PushNotificationIOS.addEventListener('notification', (notification) => {

        });
        PushNotificationIOS.addEventListener('localNotification', (notification) => {

        });
    };

    setupJPush = () => {
        JPush.init();
        JPush.addNotificationListener((message) => {
            // console.log('ReceiveNotification');
            // console.log(message);
        });

        JPush.addNotificationListener((message) => {
            //console.log(message);
            let extras = message.extras;
            if (Platform.OS === 'ios') {
                JPush.setBadge(0, () => {

                });
            } else {
                extras = JSON.parse(extras);
            }

            if (extras.action === 'upgrade') {
                Linking.openURL(AppUrl);
            }
        });

        JPush.addCustomMessagegListener((message) => {
            // console.log('addReceiveCustomMsgListener');
            // console.log(message);
        });

        JPush.getRegistrationID(registrationid => {
            //console.log('RegistrationID:'+registrationid);
            Storage.get('RegistrationID', registrationid).then(() => {
                ApiClient.post('/apns/jpush', {
                    platform: Platform.OS,
                    registrationid
                });
            });
        });
    };

    checkVersion = () => {
        //检测新版本
        ApiClient.get('/version').then(response => {
            if (response.data.version > 1.2) {
                Alert.alert(null, '红果经开区已有新的版本,是否现在升级?', [
                    {text: '取消'},
                    {text: '确定', onPress: () => Linking.openURL(AppUrl)},
                ]);
            }
        });
    };
}

const mapStateToProps = (store) => {
    const {auth, location} = store;
    return {
        auth,
        location
    };
};

const mapDispatchToProps = (dispatch) => {
    const authActions = bindActionCreators(authActionCreators, dispatch);
    const locationActions = bindActionCreators(locationActionCreators, dispatch);
    return {
        authActions,
        locationActions
    }
};

App = CodePush(App);
export default connect(mapStateToProps, mapDispatchToProps)(App);
